package com.cn.goodsadmin.dao.impl;

import com.cn.goodsadmin.common.PageQueryResult;
import com.cn.goodsadmin.dao.BaseDao;
import com.cn.goodsadmin.dao.IUserRealDao;
import com.cn.goodsadmin.po.UserRealDestDTO;
import com.cn.goodsadmin.po.Userreal;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Repository("userrealDao")
public class UserRealDaoImpl extends BaseDao<Userreal> implements IUserRealDao {

    public List<Userreal> findAllUserRealByOpenid(final String openid, boolean isuse, final int appid) throws Exception {
        final StringBuilder builder=new StringBuilder();
        builder.append("from Userreal ul where ul.cOpenid=?0");
        int flag=1;
        if(isuse){
            flag=0;
        }
        builder.append(" and ul.cIsuse="+flag);
        builder.append(" and ul.cAppid=?1");
        builder.append(" order by ul.cIsuse  asc ");
        return  getHibernateTemplate().execute(new HibernateCallback<List<Userreal>>() {
            public List<Userreal> doInHibernate(Session session) throws HibernateException {
                Query query = session.createQuery(builder.toString());
                query.setParameter(0,openid);
                query.setParameter(1,appid);
                query.setCacheable(true);
                return query.list();
            }
        });
    }

    public PageQueryResult<UserRealDestDTO> findAllUserReal(int status, int pageIndex, int pageSize, int appid) throws Exception {
        StringBuilder builder=new StringBuilder();
        builder.append("select u,r from UserInfo u,Userreal r where 1=1");
        List<Object> paraList=new ArrayList<Object>();
        builder.append(" and r.cIsuse=?0");
        paraList.add(status);
        builder.append(" and r.cOpenid=u.cOpenid");
        builder.append(" and r.cAppid=?1");
        paraList.add(appid);
        return commonQuery(builder.toString(),paraList.toArray(),pageIndex,pageSize, UserRealDestDTO.class);
    }

    @Override
    public Userreal findUserrealById(int urealid) throws Exception {
        return get(Userreal.class,urealid);
    }
}
